package com.edevp.common.security.util;

import com.edevp.common.core.util.CommonUtil;
import com.edevp.common.core.util.jwt.JwtUtil;
import com.edevp.common.redis.util.CacheUtil;
import com.edevp.common.security.constant.AuthConstants;
import com.edevp.common.security.dto.AuthTokenDTO;
import com.edevp.common.security.exception.AuthExceptionCode;
import io.jsonwebtoken.Claims;
import sun.security.util.SecurityConstants;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Lean
 * @create 2022-07-08 5:31 PM
 **/
public class TokenUtil {

	private static String getKey(String comId, int loginType, String userId){
		return String.format("%s%s:%s:%s:%s",AuthConstants.OAUTH_PREFIX ,AuthConstants.OAUTH_TOKEN_USER,comId,loginType,userId);
	}

	private static String getKey(AuthTokenDTO token){
		return getKey(token.getUser().getComId(),token.getLoginType(),token.getUser().getUserId());
	}

	public static void putToken(AuthTokenDTO token, int expire){
		CacheUtil.put(getKey(token), token, expire);
	}

//	public static AuthTokenDTO getToken(AuthTokenDTO token){
//		return CacheUtil.get(getKey(token));
//	}

	public static String getToken(HttpServletRequest request){
		// 先从url
		String token = request.getParameter(AuthConstants.OAUTH_TOKEN_URL_PARAMETER);
		if(CommonUtil.isNull(token)){
			token = request.getHeader(AuthConstants.OAUTH_TOKEN_HEADER_PARAMETER);
			if(CommonUtil.isNotNull(token)){
				if(token.startsWith(AuthConstants.OAUTH_TOKEN_HEADER_PARAMETER_BEARER)){
					//如果header中存在token，则覆盖掉url中的token, // "Bearer "之后的内容
					token = token.substring(AuthConstants.OAUTH_TOKEN_HEADER_PARAMETER_BEARER.length());
				}
				return token;
			}
		}
		return token;
	}

	/**
	 * 根据令牌获取令牌key
	 *
	 * @param token 令牌
	 * @return 用户ID
	 */
	public static String parseTokenKey(String token)
	{
		Claims claims = JwtUtil.parse(token);
		String userId = String.valueOf(claims.get(AuthConstants.OAUTH_TOKEN_USER_ID));
		String comId = String.valueOf(claims.get(AuthConstants.OAUTH_TOKEN_COMPANY_ID));
		int loginType = Integer.parseInt(String.valueOf(claims.get(AuthConstants.OAUTH_TOKEN_COMPANY_ID)));
		return getKey(comId, loginType, userId);
	}

	public static AuthTokenDTO getToken(String token){
		String key = parseTokenKey(token);
		return CacheUtil.get(key);
	}
}
